using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.OData;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using server.status_db;
[NotMapped]
public class CheckData
{


    public String 学校对结果的补充说明 { get; set; }
    public String 数据项1 { get; set; }
    public String 数据项2 { get; set; }
    public String 关联性要求 { get; set; }
    public String 指标名称1 { get; set; }
    public String 指标名称2 { get; set; }
    public String 校验结果 { get; set; }

}
[NotMapped]

public class CheckList
{



    public String 目录名称 { get; set; }

    public String 记录ID { get; set; }
    public String 字段名 { get; set; }
    public String 内容 { get; set; }
    public String 出错原因 { get; set; }


}
public class UsersController : Controller
{
    readonly ILogger<UsersController> _log;
    private status_oneContext _db;
    public UsersController(ILogger<UsersController> log, status_oneContext db)
    {
        Console.WriteLine("new controller");
        _log = log;
        _db = db;

    }

    private string Authenticate(SET_权限 user, String server)
    {
        // authentication successful so generate jwt token
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("aaaaaaaaaabbbbbbbbb");
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                    new Claim(ClaimTypes.Name, user.XM.ToString()),
                    new Claim("server", server),
            }),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);

        // remove password before returning
        return tokenHandler.WriteToken(token); ;
    }

    [AllowAnonymous]
    [HttpGet("/api/login")]
    public IActionResult Login(string XXID, string number, string password, string server)
    {
        var a = Request;
        try
        {


            var user = _db.SET_权限.SingleOrDefault(x => x.XXID == XXID && x.GH == number && x.PASSWORD == password);
            if (user == null)
            {
                using (HttpClient client = new HttpClient())
                {
                    var res = client.GetStringAsync($"http://zt.gdit.edu.cn:801/cloudApi/aipCloud.ashx?_key=9527CB44-938B-4112-BCB1-6434143D0877&_operate=apiLog&_xin={number}&_ye={password}");
                    res.Wait();

                    dynamic ss = JValue.Parse(res.Result);
                    if (ss.errmsg.ToString() == "ok")
                    {

                        dynamic temp = ss.returnData[0];
                        if (temp.UserCard != XXID)
                        {
                            return BadRequest("请选择对应的学校登录");
                        }
                        //
                        var tt = new SET_权限() { XM = "管理员" };
                        String token = Authenticate(tt, server);
                        tt.TOKEN = token;
                        return Ok(tt);
                    }
                    else
                    {
                        return BadRequest("用户名或密码错误");
                    }

                }

            }

            else
            {
                var token = Authenticate(user, server);
                user.TOKEN = token;
                return Ok(user);
            }

        }
        catch (Exception e)
        {
            _log.LogError(e.ToString());
            return BadRequest(e.Message.ToString());
        }
    }

    //
    [AllowAnonymous]
    [HttpGet("/api/getSchoolList")]
    public IActionResult GetSchoolList(string year)
    {
        try
        {

            using (HttpClient client = new HttpClient())
            {
                var res = client.GetStringAsync($"http://zt.gdit.edu.cn:801/cloudApi/aipCloud.ashx?_key=9527CB44-938B-4112-BCB1-6434143D0877&_operate=apiOfGetSchoolListServer&_year={year}");
                res.Wait();

                return Ok(res.Result);
            }
        }
        catch (Exception e)
        {
            _log.LogError(e.ToString());
            return BadRequest(e.Message.ToString());
        }
    }
    [HttpGet("/api/report")]
    public IActionResult Report(string code, string year, string password)
    {
        try
        {

            using (HttpClient client = new HttpClient())
            {
                var res = client.GetStringAsync($" http://zt.gdit.edu.cn:801/cloudApi/aipCloud.ashx?_key=9527CB44-938B-4112-BCB1-6434143D0877&_operate=apiOfSubmission&_year={year}&_xin={code}&_ye={password}");
                res.Wait();

                return Ok(res.Result);
            }
        }
        catch (Exception e)
        {
            _log.LogError(e.ToString());
            return BadRequest(e.Message.ToString());
        }
    }
    [HttpGet("/api/getMyCheckList")]
    public IActionResult getMyCheckList(string XXID, string CJPC)
    {
        try
        {

            var s = $"execute Set_P_CheckList  '{XXID}','{CJPC}',''";
            var res = _db.Query<CheckList>().FromSql(s);
            return Ok(res);

        }
        catch (Exception e)
        {
            _log.LogError(e.ToString());
            return BadRequest(e.Message.ToString());
        }
    }
    [HttpGet("/api/getCheckData")]
    public IActionResult GetCheckData(string XXID, string CJPC)
    {
        try
        {
            var s = $"execute Set_P_CheckData {XXID},{CJPC},'检测','1','2','3','4','5','6','7','8','9','10'";
            var res = _db.Query<CheckData>().FromSql(s);
            return Ok(res);
        }
        catch (Exception e)
        {
            _log.LogError(e.ToString());
            return BadRequest(e.Message.ToString());
        }
    }
    [HttpGet("/api/getReportList")]
    public IActionResult getReportList(string code, string year)
    {
        try
        {

            using (HttpClient client = new HttpClient())
            {
                var res = client.GetStringAsync($"http://zt.gdit.edu.cn:801/cloudApi/aipCloud.ashx?_key=9527CB44-938B-4112-BCB1-6434143D0877&_operate=apiOfSubmissionRecord&_year={year}&_xin={code}");
                res.Wait();
                return Ok(res.Result);
            }
        }
        catch (Exception e)
        {
            _log.LogError(e.ToString());
            return BadRequest(e.Message.ToString());
        }
    }

    //
}
